import {onMounted, onUnmounted} from 'vue'
import flvjs from 'flv.js'


let flvPlayer = null

const connect = (videoDom, sourceAddr) => {
  flvPlayer = flvjs.createPlayer({
    type: 'flv',
    url: sourceAddr
  });
  flvPlayer.on(flvjs.Events.ERROR, (errorType, errorDetail, errorInfo) => {
    destroy()
    connect(videoDom, sourceAddr)
  })
  flvPlayer.attachMediaElement(videoDom.value)
  flvPlayer.load()
  flvPlayer.play()
}

const destroy = () => {
  flvPlayer.pause()
  flvPlayer.unload()
  flvPlayer.detachMediaElement()
  flvPlayer.destroy()
  flvPlayer = null
}

export function useFlvjsVideo(videoDom, sourceAddr) {
  onMounted(() => {
    if (!flvjs.isSupported()) {
      throw Error('不支持flv.js')
    }
    connect(videoDom, sourceAddr)
  })
  onUnmounted(() => {
    destroy()
  })
}